import time
from zeep import Client
import xml.etree.ElementTree as ET
from xml.sax.saxutils import escape
import xmltodict

client = None


def get_hzfw_client():
    global client
    if client is None:
        client = Client('http://www.zjjzqrp.com/qrp/qrpws?wsdl')
    return client


def dict_to_xml(input_dict, root_tag):
    def escape_xml(val):
        if ("<" in val or ">" in val or "&" in val):
            return f"<![CDATA[{val}]]>"
        return escape(val)

    def build_xml(dict_data, parent_name):
        elements = []
        for key, value in dict_data.items():
            if isinstance(value, dict):
                elements.append(f"<{key}>{build_xml(value, key)}</{key}>")
            elif isinstance(value, list):
                items = "".join(
                    f"<{key}>{escape_xml(str(item))}</{key}>" for item in value)
                elements.append(items)
            else:
                elements.append(f"<{key}>{escape_xml(str(value))}</{key}>")
        return "".join(elements)

    return f"<{root_tag}>{build_xml(input_dict, root_tag)}</{root_tag}>"


def gen_qr_code(org_id: str, report_code: str):
    client = get_hzfw_client()
    response = client.service.preGetNotLklcQRCodeStr(
        org_id, report_code)
    print(response)
    res = xmltodict.parse(response)
    return res["xml"]


area_code_trans = {
    "市辖区": "330101",
    "上城区": "330102",
    "下城区": "330103",
    "江干区": "330104",
    "拱墅区": "330105",
    "西湖区": "330106",
    "滨江区": "330108",
    "萧山区": "330109",
    "余杭区": "330110",
    "建德市": "330182",
    "富阳市": "330183",
    "临安市": "330185",
    "桐庐县": "330122",
    "淳安县": "330127",
}


def update_report_info(org_id: str, area_code: str, area_name: str, report_code: str, report_info: dict):
    client = get_hzfw_client()
    if area_name:
        area_code = area_code_trans[area_name]
    report_info = {"BGBH": report_code} | report_info
    # report_info = {
    #     "BGBH": report_code,
    #     "YPBH": "test123",
    #     "GCMC": "测试>",
    #     "WTDW": "测试<",
    #     "JCRQ": "2024-01-01",
    #     "JCRQ2": "2024-01-02",
    #     "BGRQ": "2024-01-05",
    #     "JCNR": "测试1",
    #     "JCJL": "测试2&",
    # }
    xml_str = dict_to_xml(report_info, "xml")
    print(xml_str)
    response = client.service.afterUpNotLklcData(
        org_id, area_code, xml_str, "", 5)
    print(response)
    return response


# report_code = "test_123"
# gen_qr_code(report_code)
# time.sleep(5)
# update_report_info(report_code)
